package com.example.permissionsystem1_1.system.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 用于动态获取spring上下文对象以及各种bean的工具
 */
@Component
@Slf4j
public class SpringContextUtil implements ApplicationContextAware {
    // Spring应用上下文环境对象(一个项目只有一个)
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext=applicationContext;
    }

    /**
     * 获取上下文对象
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        log.debug("getApplicationContext");
        return applicationContext;
    }

    /**
     * 通过bean的名称获取bean对象
     * @param name
     * @param <T>
     * @return
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        log.debug("getBean by name");
        return (T) applicationContext.getBean(name);
    }

    /**
     * 通过bean的类型获取单例模式下的bean对象
     * @param clz
     * @param <T>
     * @return
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> clz) throws BeansException {
        log.debug("getBean by type");
        return (T) applicationContext.getBean(clz);
    }


}
